﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;

namespace MBBHotelReservation
{
    public partial class frmGuestProfile : Form
    {
        UnityProcessor proc = new UnityProcessor();
        Threader t = new Threader();
        UnityScript[] dat = new UnityScript[0];

        bool isEntering = false, anotherSeries = false;
        int op = 0;
        string refNum = "", fID="", fStamp="", curSeries= "", curRefNumStamp = "", type = "Individual", curRefNum = "";

        public frmGuestProfile()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }
        private void InitializeForm()
        {
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);
            t.MethodCompleted += new EventHandler(t_MethodCompleted);
            btnAdd.Click += new EventHandler(btnAdd_Click);
            btnCancel.Click += new EventHandler(btnCancel_Click);
            btnSave.Click += new EventHandler(btnSave_Click);
            btnView.Click += new EventHandler(btnView_Click);
            grdItems.DoubleClick += new EventHandler(grdItems_DoubleClick);
            chkAccount.Click += new EventHandler(chkAccount_Click);
            btnAttach.Click += new EventHandler(btnAttach_Click);
            grdItems.Enabled = false;
            States(false);
            t.MethodCall(InitLookUp);
        }

        void btnView_Click(object sender, EventArgs e)
        {
            SearchName(txtSearch.Text);
        }
        void btnAttach_Click(object sender, EventArgs e)
        {
            frmProfileLink frm = new frmProfileLink(txtRefNum.Text, type);
            frm.ShowDialog();
        }
        void chkAccount_Click(object sender, EventArgs e)
        {
            if (chkAccount.Checked == true)
            {
                type = "Corporate";
                txtContactPerson.Enabled = true;
            }
            else
            {
                type = "Individual";
                txtContactPerson.Text = "";
                txtContactPerson.Enabled = false;
            }
        }

        void grdItems_DoubleClick(object sender, EventArgs e)
        {
            txtRefNum.Enabled = false;
            refNum = grdItems.SelectedRows[0].Cells[0].Value.ToString();
            t.MethodCall(LoadData);
        }
        void btnSave_Click(object sender, EventArgs e)
        {
            States(false);
            t.MethodCall(Commit);
        }
        void btnCancel_Click(object sender, EventArgs e)
        {
            foreach (Control ctrl in grpDetail.Controls)
            {
                if (ctrl is TextBox) ((TextBox)ctrl).Text = "";
            }
            States(false);
            chkAccount.Checked = false;
            grpControl.Enabled = true;
            grdItems.Enabled = true;
            btnAttach.Visible = false;
        }
        void btnAdd_Click(object sender, EventArgs e)
        {
            isEntering = true;
            op = 0;
            grpDetail.Enabled = true;
            grpControl.Enabled = false;
            grdItems.Enabled = false;
            txtRefNum.Enabled = false;
            txtRefNum.Text = curRefNum;
            txtName.Focus();
            txtContactPerson.Enabled = false;
        }

        void t_MethodCompleted(object sender, EventArgs e)
        {
            t.SafeCall(this, delegate
            {
                switch (sender.ToString())
                {
                    case "LoadData":
                        break;
                }
            });
        }
        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(desc, id, MessageBoxButtons.OK, MessageBoxIcon.Error);
                grpDetail.Enabled = true;
                grpControl.Enabled = false;
                grdItems.Enabled = false;
                txtRefNum.Focus();
            });
        }
        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "SEARCH":
                        proc.DBPUX_Data_Fetch(out dat);
                        grdItems.DataSource = dat[0].ToDataTable();
                        txtSearch.Text = "";
                        txtSearch.Focus();
                        break;
                    case "LOADDATA":
                        proc.DBPUX_Data_Fetch(out dat);
                        UnityElement eldat;
                        dat[0].Data_Get(0, out eldat);
                        txtRefNum.Text = eldat.Data_GetField(0).ToString();
                        txtName.Text = eldat.Data_GetField(1).ToString();
                        txtAddress.Text = eldat.Data_GetField(2).ToString();
                        txtContactNumber.Text = eldat.Data_GetField(3).ToString();
                        txtContactPerson.Text = eldat.Data_GetField(5).ToString();
                        type = eldat.Data_GetField(4).ToString();

                        if (type.Equals("Individual"))
                        {
                            chkAccount.Checked = false;
                            txtContactPerson.Enabled = false;
                        }
                        else
                        {
                            chkAccount.Checked = true;
                            txtContactPerson.Enabled = true;
                        }
                        fID = eldat.Data_ID.ToString();
                        fStamp = eldat.Data_Stamp;

                        isEntering = true;
                        op = 1;
                        grpDetail.Enabled = true;
                        grpControl.Enabled = false;
                        grdItems.Enabled = false;
                        btnAttach.Visible = true;
                        txtName.Focus();
                        break;

                    case "INIT":
                        proc.DBPUX_Data_Fetch(out dat);
                        UnityElement refnum;
                        dat[0].Data_Get(0, out refnum);

                        int curDbNum = int.Parse(refnum.Data_GetField(0).ToString());
                        int StoreID = int.Parse("15000");
                        curSeries = refnum.Data_GetField(1).ToString();
                        curRefNum = curSeries + (curDbNum+StoreID).ToString("#0000");

                        if (curDbNum == 999)
                        {
                            curSeries += "A";
                            anotherSeries = true;
                        }
                        curRefNumStamp = refnum.Data_Stamp;

                        grdItems.DataSource = dat[1].ToDataTable();
                        if (!txtSearch.Focused)
                        {
                            txtSearch.AutoCompleteCustomSource.AddRange(dat[2].ToList<string>(0));
                        }

                        grpControl.Enabled = true;
                        grdItems.Enabled = true;
                        break;
                    case "COMMIT":
                        t.MethodCall(InitLookUp);
                        btnCancel_Click(null, null);
                        break;
                }
            });
        }

        //Operations
        void InitLookUp()
        {
            while (proc.IsRunning)
            {
                System.Threading.Thread.Sleep(1);
            }
            UnityScript u = new UnityScript("INIT", 4);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblgenerate");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fRefNum AS 'Reference Number', fName AS 'Name', fAddress AS 'Address', fContactNum AS 'Contact Number', fType AS 'Type', fContactPerson AS 'Contact Person', fStamp FROM tblprofile");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fName, fStamp FROM tblProfile");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void LoadData()
        {
            while (proc.IsRunning)
            {
            }
            UnityScript u = new UnityScript("LOADDATA", 5);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fRefNum AS 'Reference Number', fName AS 'Name', fAddress AS 'Address', fContactNum AS 'Contact Number', fType AS 'Type', fContactPerson AS 'Contact Person', fStamp FROM tblprofile WHERE fRefNum='{0}'", refNum));
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void SearchName(string src)
        {
            UnityScript s = new UnityScript("SEARCH", 5);
            s.Script_Add(Script.DBPUX_BEGIN);
            //I changed the query a bit to make user friendly. Used LIKE instead of =.
            s.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fRefNum AS 'Reference Number', fName AS 'Name', fAddress AS 'Address', fContactNum AS 'Contact Number', fType AS 'Type', fContactPerson AS 'Contact Person', fStamp FROM tblprofile WHERE fName LIKE '%{0}%'", src));
            s.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(s);
        }
        void Commit()
        {
            while (proc.IsRunning)
            {
            }
            UnityScript u = new UnityScript("COMMIT", 5);
            u.Script_Add(Script.DBPUX_BEGIN);
            if (op == 0)
            {
                u.Script_Add(Script.DBPUX_INSERT,
                    "tblprofile(fRefNum, fName, fAddress, fContactNum, fContactPerson, fType)",
                    new string[]{
                    txtRefNum.Text,
                    txtName.Text.Trim(),
                    txtAddress.Text,
                    txtContactNumber.Text,
                    txtContactPerson.Text,
                    type
                });
                //Update Reference Number
                if (!anotherSeries)
                {
                    u.Script_Add(Script.DBPUX_UPDATE, "tblgenerate SET " +
                        "fCurNum=fCurNum+1"
                        ,
                        "(fID='1') AND (fStamp='" + curRefNumStamp + "')");
                }
                else
                {
                    u.Script_Add(Script.DBPUX_UPDATE, "tblgenerate SET " +
                        "fCurNum='0', fCurSeries='" + curSeries + "'"
                        ,
                        "(fID='1') AND (fStamp='" + curRefNumStamp + "')");
                }
                //Transaction Log.
                //u.Script_Add(Script.DBPUX_INSERT, "tblpurchaseorderlog(fUser, fMsg, fDate)",
                //    new string[]{
                //    StoreClientModule.Common.Username,
                //    "Added supplier " + txtName.Text + " with Referene Number " + txtRefNum.Text,
                //    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                //});
            }
            else if (op == 1)
            {
                u.Script_Add(Script.PROC_ERRORSKIP, true);
                u.Script_Add(Script.DBPUX_UPDATE,
                    string.Format("tblprofile SET fRefNum='{0}', fName='{1}', fAddress='{2}', fContactNum='{3}', fContactPerson='{4}', fType='{5}'",
                    txtRefNum.Text, txtName.Text, txtAddress.Text, txtContactNumber.Text, txtContactPerson.Text, type),
                    string.Format("(fID='{0}')AND(fStamp='{1}')", fID, fStamp));
                //u.Script_Add(Script.DBPUX_UPDATE,
                //    string.Format("tblpurchaseorder SET fRefNum='{0}'", txtRefNum.Text),
                //    string.Format("(fRefNum='{0}')", refNum));
                //Transaction Log.
               // u.Script_Add(Script.DBPUX_INSERT, "tblpurchaseorderlog(fUser, fMsg, fDate)",
               //     new string[]{
               //     StoreClientModule.Common.Username,
               //     "updated supplier " + txtName.Text + " with Referene Number " + txtRefNum.Text,
               //     DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
               // });
            }
            else
            {
                u.Script_Add(Script.DBPUX_DELETE, "tblprofile", string.Format("(fID='{0}')AND(fStamp='{1}')", fID, fStamp));
            }
            
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void States(bool s)
        {
            grpControl.Enabled = s;
            grpDetail.Enabled = s;
        }


    }
}
